﻿using System;
using System.Collections.Generic;
using System.Text;
using BlueLotus7.Contract;
using BlueLotus7.Common;
using System.Runtime.Serialization;
using System.Xml;

namespace BlueLotus7.Contract
{
    [DataContract]
    public struct AuditItem : IValidate
    {
        [DataMember]
        private string auditIdentity;
        [DataMember]
        private string oldValue;
        [DataMember]
        private string newValue;

        #region Property

        /// <summary>
        /// The Audit Identity.
        /// </summary>
        public string AuditIdentity
        {
            get { return auditIdentity; }
            set { auditIdentity = value; }
        }

        /// <summary>
        /// The old value.
        /// </summary>
        public string OldValue
        {
            get { return oldValue; }
            set { oldValue = value; }
        }

        /// <summary>
        /// The new value.
        /// </summary>
        public string NewValue
        {
            get { return newValue; }
            set { newValue = value; }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="auditIdentity">The audit identity</param>
        /// <param name="oldValue">The old value.</param>
        /// <param name="newValue">The new value</param>
        public AuditItem(string auditIdentity, string oldValue, string newValue)
        {
            this.auditIdentity = auditIdentity;
            this.oldValue = oldValue;
            this.newValue = newValue;
        }

        #endregion

        public XmlNode ToXml()
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlDocumentFragment docFrag = xmlDocument.CreateDocumentFragment();
            docFrag.InnerXml = "<Item Identity=\"" + auditIdentity + "\"><OldValue><![CDATA[" + oldValue + "]]></OldValue><NewValue><![CDATA[" + newValue + "]]></NewValue></Item>";
            xmlDocument.DocumentElement.AppendChild(docFrag);
            return xmlDocument.ChildNodes[0];
        }

        #region IValidate 成员

        public bool IsValid
        {
            get
            {
                try
                {
                    Validate();
                    return true;
                }
                catch { return false; }
            }
        }

        public void Validate()
        {
            if (string.IsNullOrWhiteSpace(auditIdentity))
            {
                throw new NullOrEmptyStringException("auditIdentity");
            }
            else if (newValue == oldValue)
            {
                throw new InvalidObjectException("newValue");
            }
        }

        #endregion
    }
}
